package com.zxy.supplier_system.server.controller

import com.zxy.supplier_system.server.controller.GoodsController.GoodsDetail.SubGoodsResponse
import com.zxy.supplier_system.server.entity.Authority
import com.zxy.supplier_system.server.entity.Goods
import com.zxy.supplier_system.server.entity.GoodsUnit
import com.zxy.supplier_system.server.entity.SubGoods
import com.zxy.supplier_system.server.repository.QueryGoodsUnitResponse
import com.zxy.supplier_system.server.service.ProcurementReceiptService
import com.zxy.supplier_system.server.utils.*
import org.apache.poi.ss.usermodel.WorkbookFactory
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import java.math.BigDecimal

@RestController
@RequestMapping("procurementReceipts/{orderId}/items")
class ProcurementReceiptsItemController(
    private val procurementReceiptService: ProcurementReceiptService
) {

    data class AddProcurementReceiptsItemRequest(
        val goodsId: Int,
        val amount: Int,
        val unitId: Long?,
        val subGoodsId: Int?,
        val note: String?,
        val purchasePrice :BigDecimal = BigDecimal.ZERO,
    )

    @HasAnyAuthority(Authority.采购_入库_修改)
    @PostMapping
    fun addItem(
        @PathVariable orderId: Int,
        @RequestBody addProcurementReceiptsItemRequest: AddProcurementReceiptsItemRequest
    ) {
        this.procurementReceiptService.addItem(orderId, addProcurementReceiptsItemRequest)
    }

    @HasAnyAuthority(Authority.采购_入库_修改)
    @DeleteMapping("{goodsId}")
    fun deleteItem(@PathVariable goodsId: Int, @PathVariable orderId: Int) {
        this.procurementReceiptService.deleteItem(orderId, goodsId)
    }


    @HasAnyAuthority(Authority.采购_入库_修改)
    @DeleteMapping("{goodsId}/sub/{subGoodsId}")
    fun deleteItem(@PathVariable goodsId: Int, @PathVariable orderId: Int, @PathVariable subGoodsId: Int) {
        this.procurementReceiptService.deleteItem(orderId, goodsId, subGoodsId)
    }

    data class ValidateItemRequest(
        val amount:Int,
    )

    @HasAuthority(Authority.采购_入库_验收)
    @PatchMapping("{goodsId}/validate")
    fun validateItem(@PathVariable goodsId: Int,
                     @PathVariable orderId: Int,
                     @RequestBody request: ValidateItemRequest ){
        this.procurementReceiptService.validateItem(orderId,goodsId,request)
    }

    @HasAuthority(Authority.采购_入库_验收)
    @PatchMapping("{goodsId}/sub/{subGoodsId}/validate")
    fun validateItem(@PathVariable goodsId: Int,
                     @PathVariable orderId: Int,
                     @PathVariable subGoodsId: Int,
                     @RequestBody request: ValidateItemRequest ){
        this.procurementReceiptService.validateItem(orderId,goodsId,subGoodsId,request)
    }

    @Transactional
    class UpdateItemAmountRequest(
        val amount: Int,
        val unitId: Long?,
    )

    @HasAnyAuthority(Authority.采购_入库_入库)
    @PatchMapping("{goodsId}/amount")
    fun updateItemAmount(
        @PathVariable goodsId: Int,
        @PathVariable orderId: Int,
        @RequestBody updateItemAmountRequest: UpdateItemAmountRequest
    ) {
        return this.procurementReceiptService.updateItemAmount(goodsId, orderId, updateItemAmountRequest)
    }

    @HasAnyAuthority(Authority.采购_入库_入库)
    @PatchMapping("{goodsId}/sub/{subGoodsId}/amount")
    fun updateItemAmount(
        @PathVariable goodsId: Int,
        @PathVariable subGoodsId: Int,
        @PathVariable orderId: Int,
        @RequestBody updateItemAmountRequest: UpdateItemAmountRequest
    ) {
        return this.procurementReceiptService.updateItemAmount(goodsId, orderId, subGoodsId, updateItemAmountRequest)
    }

    @HasAnyAuthority(Authority.采购_入库_查询)
    @GetMapping
    fun queryOrderItemsInOrder(@PathVariable orderId: Int, pageable: Pageable): Page<OrderItemInOrderSummary> {
        return this.procurementReceiptService.queryOrderItemsInOrder(orderId, pageable)
    }

    @HasAnyAuthority(Authority.采购_入库_入库)
    @GetMapping("{goodsId}/exists")
    fun exists(@PathVariable goodsId: Int, @PathVariable orderId: Int): Boolean {
        return this.procurementReceiptService.exists(orderId, goodsId)
    }

    @HasAnyAuthority(Authority.采购_入库_入库)
    @GetMapping("barcodes/{barcode}/exists")
    fun exists(@PathVariable barcode: String, @PathVariable orderId: Int): Boolean {
        return this.procurementReceiptService.exists(orderId, barcode)
    }

    data class OrderItemInOrderSummary(
        val goodsId: Int,
        val name: String,
        val barcode: String,
        val amountInOrder: Int,
        val inStore: Int,
        val boxSpecification:String?,
        val units: List<QueryGoodsUnitResponse>,
        val unit: LongIdAndName?,
        val subGoods: SubGoodsResponse? = null,
        val practiceAmount:Int?,
        val price:BigDecimal,
    ) {
        companion object {
            fun fromGoodsAndAmount(goods: Goods, amount: Int,goodsUnit: GoodsUnit?,
                                   subGoods: SubGoods? = null,practiceAmount:Int?): OrderItemInOrderSummary {
                return OrderItemInOrderSummary(
                    goods.id,
                    goods.name,
                    goods.barcode,
                    amount,
                    goods.amount,
                    goods.boxSpecification,
                    goods.units.map(QueryGoodsUnitResponse::formGoodsUnit),
                    goodsUnit?.toLongIdAndName(),
                    subGoods?.let(SubGoodsResponse::fromSubGoods),
                    practiceAmount,
                    goods.price,
                )
            }
        }
    }

    @HasAnyAuthority(Authority.采购_入库_入库)
    @PostMapping("barcodes/{barcode}")
    fun addItem(@PathVariable barcode: String, @PathVariable orderId: Int): OrderItemInOrderSummary {
        return this.procurementReceiptService.addItem(orderId, barcode)
    }

    @HasAnyAuthority(Authority.采购_入库_入库)
    @PostMapping("goods/{goodsId}")
    fun addItem(@PathVariable goodsId: Int, @PathVariable orderId: Int): OrderItemInOrderSummary {
        return this.procurementReceiptService.addItem(orderId, goodsId)
    }

    @HasAuthority(Authority.采购_入库_修改)
    @PostMapping("excel/import")
    fun importFromExcel(@PathVariable orderId: Int, @RequestParam file: MultipartFile): Int {
        val workbook = WorkbookFactory.create(file.inputStream)
        val sheet = workbook.getSheetAt(0)

        val goodsItems = (1..sheet.lastRowNum).map(sheet::getRow).mapNotNull { row ->
            fun getCellValue(cellIndex: Int): String? {
                return row.getCell(cellIndex)?.displayCellString?.trim()
            }

            var cellIndex = 0
            val barcode = getCellValue(cellIndex++) ?: return@mapNotNull null
            val subGoodsNumber = getCellValue(cellIndex++)
            val amount = getCellValue(cellIndex++)?.extractFirstNumber()?.toDoubleOrNull()?.toInt() ?: return@mapNotNull null
            val unit = getCellValue(cellIndex++)
            val note = getCellValue(cellIndex++)?.nullIfBlank()
            ProcurementReceiptItemExcelItem(
                barcode,
                subGoodsNumber,
                amount,
                unit,
                note,
            )
        }

        return this.procurementReceiptService.importFromExcelItems(orderId, goodsItems)
    }


    data class ProcurementReceiptItemExcelItem(
        val barcode: String,
        val subGoodsNumber: String?,
        val amount: Int,
        val unit: String?,
        val note: String?,
    )

    data class AddProcurementItemKey(
        val goodsId: Int,
        val subGoodsId: Int?,
    )

    @HasAnyAuthority(Authority.采购_入库_修改)
    @PostMapping("batchAdd")
    fun batchAddItems(
        @PathVariable orderId: Int,
        @RequestBody itemKeys: MutableList<AddProcurementItemKey>
    ): List<OrderItemInOrderSummary> {
        return this.procurementReceiptService.batchAddItems(orderId, itemKeys)
    }

    @DeleteMapping
    fun clear(@PathVariable orderId: Int,){
        return this.procurementReceiptService.clear(orderId)
    }

}